<?php
/**
 * @abstract: Trang confirm thong tin rao vặt duoc dang
 * @author: HoanVX
 * @version $Id: post-confirm.php 91 2015-05-14 13:16:33Z voxuanhoan@gmail.com $
 */

/*
 * Template Name: Post entry confirm
 */
require_once (ABS_THEME_PATH .'helper/dbtransaction.php');

// If user is not login, rediect to login page
if (!is_user_logged_in()) {

	//'page/login.php'
	wp_redirect(get_the_permalink(33));
}

// If data duoc truyen tu page post.php fail thi quay lai trang post.php
if (!isset($_SESSION['postData'])) {
	// page/post.php
	wp_redirect(get_the_permalink(30));
}

// If click back button to come back post.php screen
if (isset($_POST['doBack'])) {

	// page/post.php
	$_SESSION['doBack'] = 'doBack';
	wp_redirect(get_the_permalink(30));

	// Update / Save information into database
} else if (isset($_POST['doSave']) && isset($_SESSION['postData'])) {

	// Create folder and move image to main folder
	$fileName = "";

	$subdir = '';
	if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
		// Generate the yearly and monthly dirs
		$time = current_time( 'mysql' );
		$y = substr( $time, 0, 4 );
		$m = substr( $time, 5, 2 );
		$subdir = "/$y/$m";
	}
	$dir = DIR_UPLOAD_IMG. $subdir;

	/// Create directory if it's not exist
	if ( ! wp_mkdir_p( $dir)) {
		// log: can not create directory
	} else {
		$targetFileDir = "";
		for ($i=1; $i<=5; $i++) {

			// If ton tai file hinh tam
			if (file_exists(convertSessionNullToBlank($_SESSION, 'postData', "imgNo{$i}", "file"))) {
				$fileSrc = $_SESSION["postData"]["imgNo{$i}"]["file"];
				$targetFileDir = $dir. "/" . basename($fileSrc);

				// Move hinh toi thu muc chinh theo dung ten
				copy($fileSrc, $targetFileDir);

				// Delete file tmp
				unlink($fileSrc);

				// Attach từng file 1 vào bài post
				attachImagesToPost(array('parentPostId' => $_SESSION['postData']['postId'], 'file' => $targetFileDir));
			}
		}

		// Add meta data for this post :city, district, price, note, postPurpose
		addPostMetas($_SESSION['postData']);

		// Remove he session lien quan: postData, post command
		session_unset();
		session_destroy();

		// redirect toi trang complete
		wp_redirect(get_the_permalink(103));
	}
}

$postData = $_SESSION['postData'];

$postId = $postData['postId'];
$imgNo1 = $imgNo2 = $imgNo3 = $imgNo4 = $imgNo5 = "";

// Initial loading data on screen
// Image 1. Nếu hình dc upload or update mới
if (file_exists(convertSessionNullToBlank($_SESSION, 'postData', "imgNo1", "file"))) {

	$imgNo1 = convertSessionNullToBlank($_SESSION, 'postData', "imgNo1", "url");
} else {

	// Get images from chotrois.com/upload/post-images/yyyy/mm/image file name.
	// if image has been registed, Image path would never contain phase "noimage.jpg"
	$imgNo1 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[0]);
}

// Image 2. Nếu hình dc upload or update mới
if (file_exists(convertSessionNullToBlank($_SESSION, 'postData', "imgNo2", "file"))) {
	$imgNo2 = convertSessionNullToBlank($_SESSION, 'postData', "imgNo2", "url");
} else {

	$imgNo2 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[1]);
}

// Image 3
if (file_exists(convertSessionNullToBlank($_SESSION, 'postData', "imgNo3", "file"))) {
	$imgNo3 = convertSessionNullToBlank($_SESSION, 'postData', "imgNo3", "url");
} else {
	$imgNo3 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[2]);
}

// Image 4
if (file_exists(convertSessionNullToBlank($_SESSION, 'postData', "imgNo4", "file"))) {
	$imgNo4 = convertSessionNullToBlank($_SESSION, 'postData', "imgNo4", "url");
} else {
	$imgNo4 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[3]);
}

// Image 5
if (file_exists(convertSessionNullToBlank($_SESSION, 'postData', "imgNo5", "file"))) {
	$imgNo5 = convertSessionNullToBlank($_SESSION, 'postData', "imgNo5", "url");
} else {
	$imgNo5 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[4]);
}


// End if Submit
add_style('css/page/post-confirm.css');
get_header();

?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="content">
	<div class="container">
		<div class="col-sm-8 col-md-8 wow fadeInRight" id="postLeft" data-wow-delay="0.4s">
		  	<h2>Xác nhận lại thông tin trước khi đăng</h2>
		  	<form action="" method="post">
			  	<table class="table table-hover">
			  		<tr>
			  			<th class="info">Chuyên mục đăng</th>
			  			<td><?php echo get_cat_name($postData['category']); ?></td>
			  		</tr>
			  		<tr>
			  			<th class="info">Khu vực đăng (Thành phố):</th>
			  			<td><?php echo ChotroiUtils::getValueByKey(CityEnum::$cities, $postData['city']); ?></td>
			  		</tr>
			  		<tr>
			  			<th class="info">Khu vực đăng (Huyện):</th>
			  			<td><?php echo ChotroiUtils::getValueByKey(CityEnum::getDistricts($postData['city']), $postData['district']); ?><br /></td>
			  		</tr>
			  		<tr>
			  			<th class="info">Tiêu đề:</th>
			  			<td><?php echo $postData['postTitle']; ?><br /></td>
			  		</tr>
			  		<tr>
			  			<th class="info">Nội dung của tin:</th>
			  			<td><?php echo $postData['postContent']; ?><br /></td>
			  		</tr>
			  		<tr>
			  			<th class="info">Bạn đăng tin để:</th>
			  			<td><?php if ($postData['postPurpose'] == 1)
									echo "Cần bán";
				      		  	else
				      		  		echo "Cần mua";
				      		 ?>
				      	</td>
			  		</tr>
			  		<tr>
			  			<th class="info">Ngày hết hạn tin đăng:</th>
			  			<td><?php echo $postData['postEndDate'];?></td>
			  		</tr>
			  		<tr>
			  			<th class="info">Hình ảnh cho tin đăng:</th>
			  			<td>
				  			<div class="row">
					      		<div class=" col-md-2 col-sm-2 img-area">
						      		<?php echo TagUtils::img(array('id'=>'img1', 'alt'=>'Hình thứ 1', 'src'=> $imgNo1, 'height'=>123, 'width'=>123));?>
						      		<label for="upImg1" class="label label-primary">Hinh 1</label>
						      	</div>
						      	<div class=" col-md-2 col-sm-2 img-area">
						      		<?php echo TagUtils::img(array('id'=>'img2', 'alt'=>'Hình thứ 2', 'src'=> $imgNo2, 'height'=>123, 'width'=>123));?>
						      		<label for="upImg2" class="label label-primary">Hinh 2</label>
						      	</div>
						      	<div class="col-md-2 col-sm-2 img-area">
						      		<?php echo TagUtils::img(array('id'=>'img3', 'alt'=>'Hình thứ 3', 'src'=> $imgNo3, 'height'=>123, 'width'=>123));?>
						      		<label for="upImg3" class="label label-primary">Hinh 3</label>
						      	</div>

						      	<div class="col-md-2 col-sm-2 img-area">
						      		<?php echo TagUtils::img(array('id'=>'img4', 'alt'=>'Hình thứ 4', 'src'=> $imgNo4, 'height'=>123, 'width'=>123));?>
						      		<label for="upImg4" class="label label-primary">Hinh 4</label>
						      	</div>
						      	<div class="col-md-2 col-sm-2 img-area">
						      		<?php echo TagUtils::img(array('id'=>'img5', 'alt'=>'Hình thứ 5', 'src'=> $imgNo5, 'height'=>123, 'width'=>123));?>
						      		<label for="upImg5" class="label label-primary">Hinh 5</label>
						      	</div>
					      	</div>
			  			</td>
			  		</tr>
			  		<tr>
			  			<th class="info">Giá của sản phẩm:</th>
			  			<td><?php echo $postData['price']; ?><br /></td>
			  		</tr>
			  		<tr>
			  			<th class="info">Ghi chú:</th>
			  			<td><?php echo $postData['note']; ?><br /></td>
			  		</tr>
			  	</table>
		    	<div class="row">
		    		<div class="form-group col-lg-12 col-md-12">
		    			<button type="submit" class="btn btn-warning" name="doSave">Tiếp tục</button>
		    			<button type="submit" class="btn btn-warning" name="doBack">Trở lại trang đăng tin</button>
		    		</div>
		    	</div>
		    </form>
		</div>
		<div class="col-sm-4 col-md-4" id="postRight">
			<h2>Lưu ý</h2>
		</div>
	</div>

	<!-- Temporary form -->
	<form action="" method="POST" id="tmpForm" style="display: none;" enctype="multipart/form-data">
		<input type="hidden" id="hdPosition" name="imgPosition">
    	<input type="hidden" name="action" value="uploadImg" id="ajaxAction"/>
	</form>

<!-- Contact's information -->
<?php get_footer("contact");?>
<!-- END Contact's information -->
</div>
<!-- content-section-ends -->
<!-- footer-section-starts -->
<?php get_footer();?>
<?php
// DEFINED LOCAL FUNCTION
/**
 * Return blank if object la ko xac dinh, else return object value theo key
 * @param unknown $object
 * @param unknown $key1
 * @param unknown $key2
 * @param string $key3
 * @return string|Ambigous <string, unknown>
 */
function convertSessionNullToBlank($object, $key1, $key2, $key3="") {
	if (!empty($key1) && !empty($key2) && !empty($key3)) {
		return isset($object[$key1][$key2][$key3]) ? $object[$key1][$key2][$key3] : "";
	} else if (!empty($key1) && !empty($key2) && empty($key3))
		return isset($object[$key1][$key2]) ? $object[$key1][$key2] : "";
	else if (!empty($key1) && empty($key2) && empty($key3))
		return isset($object[$key1]) ? $object[$key1] : "";
	else
		return "";
}

/**
 * Attach image to post
 * @param unknown $args
 */
function attachImagesToPost($args = array()) {

	$default = array(
			'file' 			=> '',
			'parentPostId'	=> 0,
	);

	$args = wp_parse_args($args, $default);

	// Check the type of file. We'll use this as the 'post_mime_type'.
	$filetype = wp_check_filetype( basename( $args['file'] ), null );

	// Get the path to the upload directory. "uploads" la ten cua folder
	$imgSliced = explode("uploads", $args['file']);

	// Chotrois.com/updload/post-images/yyyy/mm/image file.jpg
	$uploadedFileUri = ROOT_URI. 'uploads'. $imgSliced[1];

	// Prepare an array of post data for the attachment.
	$attachment = array(
			'guid'           => $uploadedFileUri,
			'post_mime_type' => $filetype['type'],
			'post_title'     => preg_replace( '/\.[^.]+$/', '', basename($args['file'])),
			'post_status'    => 'inherit'
	);

	// Insert the attachment.
	$attach_id = wp_insert_attachment( $attachment, $imgSliced[1], $args['parentPostId'] );

	// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
	require_once( ABSPATH . 'wp-admin/includes/image.php' );

	// Generate the metadata for the attachment, and update the database record.
	$attach_data = wp_generate_attachment_metadata( $attach_id, $imgSliced[1] );
	wp_update_attachment_metadata( $attach_id, $attach_data );
}

/**
 * Add or upload post meta for this post
 * // Add meta data for this post :city, district, price, note, postPurpose
 */
function addPostMetas($postData) {

	if (!update_post_meta($postData['postId'], CT_CITY, $postData['city']) )
		add_post_meta($postData['postId'], CT_CITY, $postData['city'], true) ;

	if (!update_post_meta($postData['postId'], CT_DISTRICT, $postData['district']))
	add_post_meta($postData['postId'], CT_DISTRICT, $postData['district'], true) ;

	if (!update_post_meta($postData['postId'], CT_POST_PURPOSE, $postData['postPurpose']))
		add_post_meta($postData['postId'], CT_POST_PURPOSE, $postData['postPurpose'], true);

	if (!update_post_meta($postData['postId'], CT_POST_END_DATE, $postData['postEndDate']))
		add_post_meta($postData['postId'], CT_POST_END_DATE, $postData['postEndDate'], true);

	if (!update_post_meta($postData['postId'], CT_PRICE, $postData['price'], true))
		add_post_meta($postData['postId'], CT_PRICE, $postData['price'], true);

	if (!update_post_meta($postData['postId'], CT_NOTE, $postData['note']))
		add_post_meta($postData['postId'], CT_NOTE, $postData['note'], true);
}
?>